function [lpostd,flag_ok]= lmj_postoptim(parest, parvec, parposest, indmat, funcmod, Y, trainvec, prpar, prss, solveopt, addsol, ssposest, flag_transform)
% ======================================================================
% LMJ_POSTMIN.M
% follow the structure of GENSYSPOST_VEC by Alejandro Justiniano (C)
% IN addition to putting priors on parameters, our current model put
% priors on steady state values.
%
% =======================================================================
lpostd=1e20;flag_ok=0;
% 1. Transform to go from MIN to MOD
% ----------------------------------
if flag_transform ==1
    [parest,flag_c]=check_min(parest,indmat);
    if flag_c==0;disp('Problems with transformed coefficients');return;end
end
parvec(parposest)=parest;
% 2. Solve model
% -------------------------------------
[G1, impact, C,eu,SDX,ZZ, junk, ssvec]=feval(funcmod,parvec,solveopt,addsol);
if ~isequal(eu(:),[1;1]);
    return
end
% 3. Demean data
% ---------------------------------------
[T,nn]=size(Y);
if any(C~=0)==1;
    Y=Y-repmat((ZZ*C)',[T 1]);
end;
Y=Y';
MM=impact*(SDX');
try
    pshat=disclyap_fast(G1,MM*(MM'));
    if ~isempty(find(isnan(pshat))~=0)
        disp('PSHAT contains Nan entries')
        return
    end
catch
    disp('Warning! Problems with initialization in GENSYSPOST_VEC');
    return;
end
sTT=zeros(size(G1,1),T+1); 
sTT(:,1)=zeros(size(G1,1),1);
lht=zeros(T,1);
try
    for ii=1:T;
        [sTT(:,ii+1),pshat,lht(ii)]=kf(Y(:,ii),ZZ,sTT(:,ii),pshat,G1,MM);
    end
catch
    disp('Warning! Problems with Kalman filter in GENSYSPOST');
    MException; 
    return
end
%likel=-0.5*length(lht)*nn*log(2*pi)+sum(lht);
likel=sum(lht(trainvec(1):trainvec(2)));
if isinf(abs(likel));
    disp('Likelihood is infinite!')
    return
end
%% Prior Density of Parameters
lpriord=sum(priordens(parvec, prpar.prior, prpar.alphap, prpar.betap, prpar.lbnd, prpar.ubnd));
if isinf(abs(lpriord))==1;return;end
%% Prior Density on Steady State
if ~isempty(ssposest)
    lpriord_ss = sum(priordens(ssvec(ssposest), prss.prior, prss.alphap, prss.betap, prss.lbnd, prss.ubnd));
else
    lpriord_ss=0;
end

if isinf(abs(lpriord_ss))==1;return;end
%% log likelihood
lpostd = -(lpriord + lpriord_ss + likel);